﻿Type.registerNamespace('MS.InformationManagement.StandardDocumentIDConfigurator');
MS.InformationManagement.StandardDocumentIDConfigurator.FetchTimeout = null;
MS.InformationManagement.StandardDocumentIDConfigurator.ConsecutieFieldCode = 1;

MS.InformationManagement.StandardDocumentIDConfigurator.Initialize = function (docTypeIdControlID, docTypeNameControlID, docTypeCodeControlID, configAreaControlID, availableFieldsAreaControlID, submitControlID
    , strategyControlID) {
    $('body').ajaxloader({ fullscreen: true, baseurl: '/sites/docs/', autoshow: false });
    MS.InformationManagement.Services.DocumentIdConfigService.set_path('/sites/docs/' + MS.InformationManagement.Services.DocumentIdConfigService.get_path());

    var configArea = $('#' + configAreaControlID);
    var availableFieldsArea = $('#' + availableFieldsAreaControlID);
    var docTypeNameControl = $('#' + docTypeNameControlID);
    var docTypeCodeControl = $('#' + docTypeCodeControlID);
    var docTypeIdControl = $('#' + docTypeIdControlID);
    var submitControl = $('#' + submitControlID);
    var strategyControl = $('#' + strategyControlID);

    configArea
        .sortable({ revert: true })
        .droppable({ accept: 'div', drop: MS.InformationManagement.StandardDocumentIDConfigurator.FromAvailableToConfigDrop });
    availableFieldsArea
        .droppable({ accept: 'div', drop: MS.InformationManagement.StandardDocumentIDConfigurator.FromConfigToAvailableDrop })
        .find('div').draggable({ revert: 'invalid' });

    docTypeNameControl.bind("propertychange keyup input paste",
        function (event) {
            clearTimeout(MS.InformationManagement.StandardDocumentIDConfigurator.FetchTimeout);
            MS.InformationManagement.StandardDocumentIDConfigurator.FetchTimeout = setTimeout(
                function () {
                    var pageIsValid = Page_ClientValidate('docConfigSubmit');
                    if (pageIsValid != true) { return; }
                    switch (strategyControl.val()) {
                        case 'Create':
                            MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnCreate(docTypeNameControl, docTypeCodeControl, submitControl);
                            break;
                        case 'Update':
                            MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnUpdate(docTypeIdControl, docTypeNameControl, docTypeCodeControl, submitControl);
                            break;
                    }
                }, 1000);
        }
    );

    docTypeCodeControl.bind("propertychange keyup input paste",
        function (event) {
            clearTimeout(MS.InformationManagement.StandardDocumentIDConfigurator.FetchTimeout);
            MS.InformationManagement.StandardDocumentIDConfigurator.FetchTimeout = setTimeout(
                function () {
                    var pageIsValid = Page_ClientValidate('docConfigSubmit');
                    if (pageIsValid != true) { return; }
                    switch (strategyControl.val()) {
                        case 'Create':
                            MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnCreate(docTypeNameControl, docTypeCodeControl, submitControl);
                            break;
                        case 'Update':
                            MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnUpdate(docTypeIdControl, docTypeNameControl, docTypeCodeControl, submitControl);
                            break;
                    }
                }, 1000);
        }
    );

    submitControl.click(function () {
        var pageIsValid = Page_ClientValidate('docConfigSubmit');
        if (pageIsValid != true) { return; }
        switch (strategyControl.val()) {
            case 'Create':
                MS.InformationManagement.StandardDocumentIDConfigurator.SaveNewDocType(docTypeNameControl, docTypeCodeControl, configArea, submitControl);
                break;
            case 'Update':
                MS.InformationManagement.StandardDocumentIDConfigurator.UpdateDocType(docTypeIdControl, docTypeNameControl, docTypeCodeControl, configArea, submitControl);
                break;
        }
    });

}

MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnCreate = function (docTypeNameControl, docTypeCodeControl, submitControl) {
    MS.InformationManagement.Services.DocumentIdConfigService.AlreadyExistsOnCreation(
        docTypeNameControl.val(),
        docTypeCodeControl.val(),
        MS.InformationManagement.StandardDocumentIDConfigurator.OnExistsOnCreateSuccess,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnAjaxError,
        { submitControl: submitControl }
    );
}

MS.InformationManagement.StandardDocumentIDConfigurator.DocExistsOnUpdate = function (docTypeIdControl, docTypeNameControl, docTypeCodeControl, submitControl) {
    MS.InformationManagement.Services.DocumentIdConfigService.AlreadyExistsOnUpdate(
        docTypeNameControl.val(),
        docTypeCodeControl.val(),
        parseInt(docTypeIdControl.val()),
        MS.InformationManagement.StandardDocumentIDConfigurator.OnExistsOnCreateSuccess,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnAjaxError,
        { submitControl: submitControl }
    );
}


MS.InformationManagement.StandardDocumentIDConfigurator.UpdateDocType = function (docTypeIdControl, docTypeNameControl, docTypeCodeControl, configArea,
submitControl) {
    var configFields = new Array();
    var includesMandatoryField = false;
    configArea.find('div').each(function (index) {
        var currentElement = $(this);
        var currentConfigField = {
            Title: currentElement.find('span')[0].innerHTML,
            FieldId: parseInt(currentElement.find('input[type="hidden"]')[0].value),
            ConfigItemId: parseInt(currentElement.find('input[type="hidden"]')[1].value),
            Order: index
        };
        if (currentConfigField.FieldId === MS.InformationManagement.StandardDocumentIDConfigurator.ConsecutieFieldCode) { includesMandatoryField = true; }
        configFields.push(currentConfigField);
    });
    if (includesMandatoryField == false) {
        MS.InformationManagement.Common.ShowStatus('Debe agregar el campo de "Consecutivo" antes de almancenar la estructura de generación del número de radicado.', 'yellow', 6000);
        return;
    }
    $('body').ajaxloader('show');
    submitControl.attr('disabled', 'disabled');

    MS.InformationManagement.Services.DocumentIdConfigService.Update(
        parseInt(docTypeIdControl.val()),
        docTypeNameControl.val(),
        docTypeCodeControl.val(),
        configFields,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnUpdateSuccess,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnAjaxError,
        { submitControl: submitControl }
    );
}


MS.InformationManagement.StandardDocumentIDConfigurator.SaveNewDocType = function (docTypeNameControl, docTypeCodeControl, configArea, submitControl) {
    var configFields = new Array();
    var includesMandatoryField = false;
    configArea.find('div').each(function (index) {
        var currentElement = $(this);
        var currentConfigField = {
            Title: currentElement.find('span')[0].innerHTML,
            FieldId: parseInt(currentElement.find('input[type="hidden"]')[0].value),
            Order: index
        };
        if (currentConfigField.FieldId === MS.InformationManagement.StandardDocumentIDConfigurator.ConsecutieFieldCode) { includesMandatoryField = true; }
        configFields.push(currentConfigField);
    });
    if (includesMandatoryField == false) {
        MS.InformationManagement.Common.ShowStatus('Debe agregar el campo de "Consecutivo" antes de almancenar la estructura de generación del número de radicado.', 'yellow', 6000);
        return;
    }
    $('body').ajaxloader('show');
    submitControl.attr('disabled', 'disabled');

    MS.InformationManagement.Services.DocumentIdConfigService.Add(
        docTypeNameControl.val(),
        docTypeCodeControl.val(),
        configFields,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnAddSuccess,
        MS.InformationManagement.StandardDocumentIDConfigurator.OnAjaxError,
        { submitControl: submitControl }
    );
}

MS.InformationManagement.StandardDocumentIDConfigurator.OnExistsOnCreateSuccess = function (result, userstate) {
    $('body').ajaxloader('hide');
    if (result === true) {
        MS.InformationManagement.Common.ShowStatus('El nombre del tipo de radicado / codigo de tipo de radicado no se encuentran disponibles.', 'yellow', 6000);
        userstate.submitControl.attr('disabled', 'disabled');
    }
    if (result === false) {
        MS.InformationManagement.Common.ShowStatus('El nombre del tipo de radicado / codigo de tipo de radicado se encuentran disponibles.', 'blue', 6000);
        userstate.submitControl.attr('disabled', '');
    }
}

MS.InformationManagement.StandardDocumentIDConfigurator.OnUpdateSuccess = function (result, userstate) {
    $('body').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('El tipo de radicado ha sido actualizado exitosamente.', 'green', 6000);
    setTimeout(function () { window.location.href = window.location.href.split("?")[0]; }, 6000);
}

MS.InformationManagement.StandardDocumentIDConfigurator.OnAddSuccess = function (result, userstate) {
    $('body').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('El tipo de radicado ha sido agregado exitosamente.', 'green', 6000);
    setTimeout(function () { window.location.href = window.location.href.split("?")[0]; }, 6000);
}

MS.InformationManagement.StandardDocumentIDConfigurator.OnAjaxError = function (exception, userstate) {
    $('body').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
    if (userstate && typeof userstate != 'undefined') {
        userstate.submitControl.attr('disabled', '');
    }
}

MS.InformationManagement.StandardDocumentIDConfigurator.FromAvailableToConfigDrop = function (event, ui) {
    var draggedElement = ui.draggable;
    var droppingTarget = $(event.target);

    if (draggedElement.hasClass('config-label')) {
        //se arrastra uno de los que existen
    }
    if (draggedElement.hasClass('available-label')) {
        var newElement = $('<div class="config-element-draggable config-label"><span>'
            + draggedElement.find('span')[0].innerHTML
            + '</span><input type="hidden" value="'
            + draggedElement.find('input[type="hidden"]')[0].value + '" />'
            + '<input type="hidden" value="'
            + draggedElement.find('input[type="hidden"]')[1].value + '" /></div>');
        droppingTarget.append(newElement);
        draggedElement.remove();
    }
}

MS.InformationManagement.StandardDocumentIDConfigurator.FromConfigToAvailableDrop = function (event, ui) {
    var draggedElement = ui.draggable;
    var droppingTarget = $(event.target);

    if (draggedElement.hasClass('config-label')) {
        var newElement = $('<div class="available-label"><span>'
            + draggedElement.find('span')[0].innerHTML
            + '<input type="hidden" value="'
            + draggedElement.find('input[type="hidden"]')[0].value + '" />'
            + '</span><input type="hidden" value="'
            + draggedElement.find('input[type="hidden"]')[1].value + '" /></div>');
        droppingTarget.append(newElement);
        newElement.draggable({ revert: 'invalid' });
        draggedElement.remove();
    }
    if (draggedElement.hasClass('available-label')) {

    }
}